<?php

class Lw_auth
{
    protected $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
        $this->CI->load->database();
        $this->CI->load->library('lw_js');
        $this->CI->load->library('lw_db',array('tb_name'=>'tb_method'),'tb_method');
        $this->CI->load->library('lw_db',array('tb_name'=>'tb_role_power'),'tb_role_power');
    }

    public function check()
    {
        $segments = $this->CI->uri->segments;// 获取URL参数
        // 登录状态校验
        $this->checkLogined($segments);
        // 管理员权限校验
        $this->checkRolePower($segments);
    }

    protected function checkLogined($segments)
    {
        $this->CI->load->helper('cookie');
        // 如果管理员ID失效
        if ($this->CI->session->adminId != null && $this->CI->session->adminId != ""){ return;}
        $controller = (isset($segments[1]))?$segments[1]:"home";
        $method = (isset($segments[2]))?$segments[2]:"index";
        $rowController = $this->CI->tb_method->get_one(array('parent_id'=>0,'name'=>$controller));
        $rowMethod = $this->CI->tb_method->get_one(array('parent_id'=>$rowController['id'],'name'=>$method,'is_menu'=>0));
        // 只有记录的非菜单事件才会ajax 返回，其他都是alert
        if($rowMethod){
            echo $this->CI->lw_load->jsonResult(false,array('msg'=>'登录状态失效，操作','relogin'=>true),true);
            exit;
        }
        $backUrl = "";
        if($segments){
            for($i=1;$i<=sizeof($segments);$i++){
                $url = (isset($segments[$i]))?$segments[$i]:"";
                if($url){
                    if($backUrl==""){
                        $backUrl = $url;
                    }else{
                        $backUrl = $backUrl.'/'.$url;
                    }
                }
            }
        }else{
            $backUrl = 'home/index';
        }
        $this->CI->session->set_userdata('backUrl',$backUrl);
        // 如果是页面，先提示后跳转
        $this->CI->lw_js->alert($backUrl.'登录状态失效,请重新登陆');
        $this->CI->lw_js->jump(site_url('login/index/2'));
    }

    protected function checkRolePower($segments)
    {
        // 1. 最高权限不需要鉴权
        $topRole = $this->CI->session->userdata('topRole');
        if($topRole){return;}
        // 不是最高权限管理员；获取角色ID
        $roleId = $this->CI->session->userdata('roleId');
        // 执行鉴权工作
        $result = $this->getResult($roleId,$segments);
        // 如果鉴权成功，返回跳出即可
        if($result['success']){return;}
        // 鉴权不成功：即没有此操作权限，程序将 exit 跳出，停止执行下面工作
        switch($result['type']){
            case 0:
                echo $this->CI->lw_load->jsonResult(false,array('msg'=>"注意，你没有权限执行{$result['describe']}操作！"));
                break;
            case 1:
                $this->CI->lw_js->alert("注意，你没有访问{$result['describe']}的权限！");
                $this->CI->lw_js->goHome();
                break;
        }
        exit;
    }

    /**
     * @param $roleId：角色ID
     * @param $segments：请求参数：Controller 和 method
     * @return array
     */
    private function getResult($roleId,$segments)
    {
        $controller = (isset($segments[1]))?$segments[1]:"home";
        $method = (isset($segments[2]))?$segments[2]:"index";
        // 判断是否是默认
        $isDefault = $this->isDefault($controller,$method);
        // 是默认控制器或方法
        if($isDefault){return array('success'=>true);}
        // 不是默认控制器跟方法
        $rowController = $rowController = $this->CI->tb_method->get_one(array('parent_id'=>0,'name'=>$controller));
        $rowMethod = $this->CI->tb_method->get_one(array('parent_id'=>$rowController['id'],'name'=>$method));
        $hasPower = $this->CI->tb_role_power->get_one(array('role_id'=>$roleId,'method_id'=>$rowMethod['id']));
        if($hasPower){
            return array('success'=>true);
        }else{
            $describe = $rowController['describe'].'-'.$rowMethod['describe'];
            return array('success'=>false,'type'=>$rowMethod['is_menu'],'describe'=>$describe);
        }
    }

    /** 判断控制器跟方法是否为默认，是 return true 否 return false
     * @param $controller:控制器名称
     * @param $method：方法名称
     * @return bool
     */
    private function isDefault($controller,$method)
    {
        $rowController = $this->CI->tb_method->get_one(array('parent_id'=>0,'name'=>$controller));
        if($rowController['is_default']==1){return true;}
        $rowMethod = $this->CI->tb_method->get_one(array('parent_id'=>$rowController['id'],'name'=>$method));
        return ($rowMethod['is_default']==1)? true:false;
    }
    
}